const {
    callContainerApi,
    getUuid,
    env,
    showErrorToast,
    showSuccessToast
} = require("../../utils/util.js")
Page({
    data: {
        id: null,
        name: '',
        desc: '',
        specifications: [], // 用于存储多个{商品单位，单位价格}对
        Merchantid: null,
        pictures: [],
        subCategoryId: null,
        firstPic: "",
        isEditMode: false // 标记是否为编辑模式
    },

    onLoad(options) {
        const {
            item,
            userInfo,
            subCategoryId
        } = options;

        // 解析参数
        if (item) {
            const decodedItem = decodeURIComponent(item);
            const parsedItem = JSON.parse(decodedItem);
            const merchandiseId = parsedItem.id
            callContainerApi(`/product/merchandise?merchandiseId=${merchandiseId}`, "GET", null)
                .then(res => {
                    console.log(res)
                    this.setData({
                        ...res.data.data
                    })
                })
        }

        const parsedUserInfo = JSON.parse(decodeURIComponent(userInfo));
        this.setData({
            Merchantid: parsedUserInfo,
            subCategoryId: subCategoryId
        });
    },

    onNameInput(e) {
        this.setData({
            name: e.detail.value
        });
    },
    onDescInput(e) {
        this.setData({
            desc: e.detail.value
        });
    },
    onSpecInput(e) {
        const index = e.currentTarget.dataset.index
        const spec = this.data.specifications
        spec[index].spec = e.detail.value
        this.setData({
            specifications: spec
        });
    },
    onPriceInput(e) {
        const index = e.currentTarget.dataset.index
        const spec = this.data.specifications
        // spec[index].price = parseFloat(e.detail.value) || 0
        spec[index].price = e.detail.value
        this.setData({
            specifications: spec
        });
    },

    async chooseImage() {
        const {
            pictures,
            merchandiseId
        } = this.data;

        try {
            // 选择媒体文件
            const res = await new Promise((resolve, reject) => {
                wx.chooseMedia({
                    mediaType: ['image'],
                    maxDuration: 9,
                    success: resolve,
                    fail: reject
                });
            });

            let pics = []; // 用于存储上传后的图片信息

            // 使用 Promise.all 等待所有上传完成
            const uploadPromises = res.tempFiles.map(async (item) => {
                const path = item.tempFilePath;
                const tempName = path.substr(path.lastIndexOf("/") + 1);
                const suffix = tempName.substr(tempName.indexOf(".") + 1);
                const cloudPath = getUuid() + "." + suffix;
                if (!this.data.firstPic) {
                    // 保存第一张图片，待作为该商品的缩略图
                    this.setData({
                        firstPic: path
                    })
                }
                const uploadRes = await wx.cloud.uploadFile({
                    cloudPath: cloudPath,
                    filePath: path,
                    config: {
                        env: 'prod-8g6k5cfre7cd634b'
                    }
                });

                return {
                    fileId: uploadRes.fileID,
                    suffix: suffix
                };
            });

            // 等待所有上传完成
            pics = await Promise.all(uploadPromises);

            console.log(pics)

            // 批量传入后端获取id
            await callContainerApi(`/product/oss`, "POST", pics)
                .then(res => {
                    console.log(res)
                    for (const item of res.data.data) {
                        pictures.push({
                            ossId: item.id,
                            fileId: item.fileId
                        })
                    }
                    // 使用 setData 更新 pictures，确保视图更新
                    this.setData({
                        pictures: pictures
                    });
                }).catch(error => {
                    console.log(error)
                    showErrorToast("后端返回数据格式错误");
                })
        } catch (error) {
            console.error('选择或上传图片失败:', error);
            showErrorToast("选择或上传图片失败，请重试");
        }
    },

    removeImage(e) {
        const index = e.currentTarget.dataset.index;
        let pictures = this.data.pictures
        let fileList = []
        console.log(pictures)
        fileList.push(pictures[index].fileId)
        wx.cloud.deleteFile({
            fileList: fileList
        }).then(res => {
            pictures.splice(index, 1)
            this.setData({
                pictures
            })
        })
    },

    // ************************************************
    addSpecification() {
        const specifications = this.data.specifications;
        specifications.push({
            spec: null,
            price: null,
        });
        this.setData({
            specifications
        });
    },
    // ************************************************

    removeSpecification(e) {
        const index = e.currentTarget.dataset.index;
        const specifications = this.data.specifications;
        specifications.splice(index, 1);
        // 移除后重新更新序号
        const updatedSpecifications = specifications.map((spec, newIndex) => ({
            ...spec,
            index: newIndex + 1
        }));
        this.setData({
            specifications: updatedSpecifications
        });
    },

    async saveGoods() {
        const {
            id,
            name,
            desc,
            specifications,
            pictures,
            subCategoryId,
            firstPic
        } = this.data;

        // 表单验证
        if (!name) {
            return wx.showToast({
                title: '请填写完整信息',
                icon: 'none'
            });
        }

        // 构造请求体
        const requestData = {
            MerchandiseId: id,
            name,
            pictureIds: pictures.map(a => a.ossId).join(","), // 实际应替换为上传后的图片ID
            desc,
            specifications: specifications
        };


        // 保存商品信息
        callContainerApi(`/product/merchandise?categoryId=${subCategoryId}`, "POST", requestData)
            .then(res => {
                console.log(res)
                const merchandiseId = res.data.data.data
                wx.cloud.uploadFile({
                    cloudPath: merchandiseId+'',
                    filePath: firstPic,
                    config: {
                        env: 'prod-8g6k5cfre7cd634b'
                    }
                });
                // 标记需要刷新商品列表
                wx.setStorageSync('needRefreshGoodsList', true);
                // 显示成功提示并返回
                showSuccessToast('保存成功')
                setTimeout(() => wx.navigateBack(), 1500);
            }).catch(error => {
                console.error('保存商品失败:', error);
                showErrorToast('保存失败，请重试', )
            })
    }
});